<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery"  size="mini">
      <el-form-item >
        <el-input v-model="listQuery.name" clearable class="filter-item" placeholder="请输入名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
        <el-button style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" border highlight-current-row >
      <el-table-column label="角色名" prop="name" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="remark" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :destroy-on-close="true">
      <el-form ref="postForm" :rules="rules" :model="postForm" label-width="150px">
        <el-form-item label="角色名" prop="name" style="width: 400px;">
          <el-input v-model="postForm.name" class="filter-item"/>
        </el-form-item>
        <el-form-item label="权限" prop="menu_ids" style="width: 400px;margin-bottom: 20px;">
          <el-checkbox v-model="checked" @change="chooseAllOrNo">全选/反选</el-checkbox>
          <el-tree :props="props"
                   :data="permissionList" node-key="id"
                   ref="permissionTree"
                   @check-change="permissionChage"
                   show-checkbox>
          </el-tree>
        </el-form-item>
        <el-form-item label="描述"  style="width: 400px;">
          <el-input v-model="postForm.remark" type="textarea" :rows="2" placeholder="请输入内容" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { feachRoleList, editRole } from '@/api/role.js'
import { feachMenusList } from '@/api/menu.js'
import Pagination from '@/components/Pagination'
const defaultForm = {
  id: '',
  name: '',
  menu_ids: [],
  remark: '',
}
export default {
  name: 'ComplexTable',
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      postForm: Object.assign({}, defaultForm),
      checked: false,
      permissionList: [],
      permission_temp: [],
      props: {
        label: 'display_name',
        children: 'children'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      listQuery: {
        name: '',
        page: 1,
        limit: 20,
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        menu_ids: [{ required: true, message: '请选择权限', trigger: 'change' }]
      },
    }
  },
  created() {
    this.getList()
    this.getMenuList()
  },
  methods: {
    //角色列表
    async getList() {
      const data = await feachRoleList(this.listQuery)
      if (data.code == 200) {
        this.list = data.data.list
      } else {
        this.$message.error(data.userMsg)
      }
    },
    //获取菜单数据
    async getMenuList() {
      const data = await feachMenusList(this.listQuery)
      if (data.code == 200) {
        const menus = data.data.list
        this.permissionList = menus
      } else {
        this.$message.error(data.userMsg)
      }
    },
    //筛选
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    //新增
    handleCreate() {
      this.dialogStatus = 'create'
      this.postForm = Object.assign({}, defaultForm),
      this.dialogFormVisible = true
    },
    createData() {
      this.postForm.menu_ids = this.permission_temp
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.addOrUpdateRole(this.postForm)
          this.dialogFormVisible = false
        }
      })
    },
    //新增/编辑
    async addOrUpdateRole(data) {
      const response = await editRole(data)
      if (response.code === 200){
        this.$message.success('操作成功')
        this.handleFilter()
      } else {
        this.$message.error(response.userMsg)
      }
      return response
    },
    //更新
    handleUpdate(row) {
      var that = this
      let checked_keys = []
      that.postForm.id = row.id
      that.postForm.name = row.name
      that.postForm.remark = row.remark
      that.permission_temp =[]
      if (row.menus.length > 0) {
        row.menus.forEach(function (item,index){
          that.permission_temp.push(item.id)
          if(item.children.length > 0) {
            item.children.forEach(function (item,index) {
              checked_keys.push(item.id)
              that.permission_temp.push(item.id)
            })
          }
        })
        this.$nextTick(() =>{
          that.$refs.permissionTree.setCheckedKeys(checked_keys)
        })
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateData() {
      this.postForm.menu_ids = this.permission_temp
      const data =JSON.parse(JSON.stringify(this.postForm));
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.addOrUpdateRole(data)
          this.dialogFormVisible = false
        }
      })
    },
    cancelForm() {
      this.postForm = Object.assign({}, defaultForm)
      this.dialogFormVisible = false
      this.checked = false
    },
    //全选/反选
    chooseAllOrNo(e) {
      var that = this
      if(e) {
        that.$refs.permissionTree.setCheckedNodes(this.permissionList)
      } else {
        that.$refs.permissionTree.setCheckedKeys([]);
      }
    },
    permissionChage(data, checked, indeterminate) {
      var that = this
      const temp = []
      //获取当前半选节点
      const halfCheckCat = this.$refs.permissionTree.getHalfCheckedNodes()
      //获取当前选中节点
      const checkCat = this.$refs.permissionTree.getCheckedNodes()
      halfCheckCat.forEach(function(item, index) {
        temp.push(item.id)
      })
      checkCat.forEach(function(item, index) {
        temp.push(item.id)
      })
      that.permission_temp = temp
      that.check_box()
    },
    check_box() {
      let nodes = []
      this.permissionList.forEach(function (item,index){
        nodes.push(item.id)
        if (item.children.length > 0) {
          item.children.forEach(function (item,index){
            nodes.push(item.id)
          })
        }
      })
      if (nodes.length === this.permission_temp.length){
        this.checked = true
      }else {
        this.checked = false
      }
    }
  }
}
</script>
